import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, DatePicker, Select, Modal } from 'antd'
import { UpOutlined, DownOutlined, DownloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import moment from 'moment'
import { addWindow } from '@redux/actions'
import style from '@pages/filingCaseManage/CaseManage.module.less'
import { getEmployeeListRequest } from './ajax'
import { awaitWrap, formatMoney } from '@js/tool'
import { json2Excel } from '@js/excel'
import nStyle from './Index.module.less'

const { Item } = Form
const { Option } = Select
const { confirm } = Modal

const layout = {
  labelCol: { flex: '100px' }
}

// 获取表格字段配置
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      sorter: true
    },
    {
      title: '结案时间',
      dataIndex: 'closure_datetime',
      key: 'closure_datetime',
      width: 120,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      },
      sorter: true
    },
    {
      title: '受理费',
      dataIndex: 'fee_acceptance',
      key: 'fee_acceptance',
      align: 'right',
      render: (v) => {
        return formatMoney(v)
      }
    },
    {
      title: '处理费',
      dataIndex: 'fee_processing',
      key: 'fee_processing',
      align: 'right',
      render: (v) => {
        return formatMoney(v)
      }
    },
    {
      title: '主办秘书',
      dataIndex: 'processer',
      key: 'processer',
      sorter: true
    },
    // {
    //   title: '仲裁员交通补贴',
    //   dataIndex: 'subsidy_amount',
    //   key: 'subsidy_amount',
    //   align: 'right',
    //   render: (v) => {
    //     return formatMoney(v, '')
    //   }
    // },
    {
      title: '仲裁员报酬',
      dataIndex: 'real_amount',
      key: 'real_amount',
      align: 'right',
      render: (v) => {
        return formatMoney(v, '')
      }
    },
    // {
    //   title: '代扣会员费',
    //   dataIndex: 'membership_amount',
    //   key: 'membership_amount',
    //   align: 'right',
    //   render: (v) => {
    //     return formatMoney(v, '')
    //   }
    // },
    // {
    //   title: '仲裁员裁决书制作',
    //   dataIndex: 'closuredoc_amount',
    //   key: 'closuredoc_amount',
    //   align: 'right',
    //   render: (v) => {
    //     return formatMoney(v, '')
    //   }
    // },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark'
    }
  ]
}

class SimpleSearch extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    arbitratorList: [],
    employeeList: [],
    condition: [],
    selectedRowKeys: [],
    selectedRows: [],
    statusList: [],
    orderField: '',
    order: '',
    closuredocAmountSum: 0,
    feeAcceptanceSum: 0,
    feeProcessingSum: 0,
    membershipAmountSum: 0,
    realAmountSum: 0,
    subsidyAmountSum: 0,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    }
  }

  formRef = React.createRef()

  getParams (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination, orderField, order } = this.state
    const { current, pageSize } = pagination
    const condition = []
    this.setState({ loading: true })
    if (form.processerid) {
      condition.push({ k: 'processerid', o: '=', v: form.processerid })
    }
    if (form.caseno_desc) {
      condition.push({ k: 'c.caseno_desc|c.counter_caseno_desc', o: 'like', v: `%${form.caseno_desc}%` })
    }
    if (form.beginTime) {
      condition.push({ k: 'closure_datetime', o: '>=', v: Math.floor(moment(form.beginTime.format('YYYY-MM-DD')).valueOf() / 1000) })
    }
    if (form.endTime) {
      condition.push({ k: 'closure_datetime', o: '<=', v: Math.floor(moment(form.endTime.format('YYYY-MM-DD') + ' 23:59:59').valueOf() / 1000) })
    }
    if (form.oBeginTime) {
      condition.push({ k: 'fi.create_datetime', o: '>=', v: Math.floor(moment(form.oBeginTime.format('YYYY-MM-DD')).valueOf() / 1000) })
    }
    if (form.oEndTime) {
      condition.push({ k: 'fi.create_datetime', o: '<=', v: Math.floor(moment(form.oEndTime.format('YYYY-MM-DD') + ' 23:59:59').valueOf() / 1000) })
    }
    this.setState({
      condition
    })
    delete form.beginTime
    delete form.endTime
    const data = {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }
    if (orderField && order) {
      data.order = order === 'ascend' ? 'asc' : 'desc'
      data.order_field = orderField
    }
    return data
  }

  // 获取案件数据
  getTableData (form) {
    const { pagination } = this.state
    const { current, pageSize } = pagination
    const params = this.getParams(form)
    this.$get('/api/xapc/remuneration/caseRemuneration', {
      params
    }).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          },
          closuredocAmountSum: res.data.closuredoc_amount_sum,
          feeAcceptanceSum: res.data.fee_acceptance_sum,
          feeProcessingSum: res.data.fee_processing_sum,
          membershipAmountSum: res.data.membership_amount_sum,
          realAmountSum: res.data.real_amount_sum,
          subsidyAmountSum: res.data.subsidy_amount_sum
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      condition: [],
      selectedRowKeys: [],
      selectedRows: []
    })
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const c = this.formRef.current
    const { formData = {} } = this.props.meta || {}
    c.resetFields()
    c.setFieldsValue(formData)
    c.submit()
  }

  async initEmpolyeeList () {
    const [e, d] = await awaitWrap(getEmployeeListRequest())
    if (e === null && d !== null) {
      this.setState({ employeeList: d })
    }
  }

  // 二次弹框确认下载excel
  confirmDownload () {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要导出excel吗？',
      onOk: () => {
        this.downloadExcel()
      }
    })
  }

  // 获取当前查询条件的全部数据，并下载excel
  downloadExcel () {
    const current = 1
    const pageSize = 1000000
    const hide = message.loading('导出中', 300)
    const params = {
      current,
      page_size: pageSize,
      condition: JSON.stringify(this.state.condition)
    }
    const { orderField, order } = this.state
    if (orderField && order) {
      params.order = order === 'ascend' ? 'asc' : 'desc'
      params.order_field = orderField
    }
    this.$get('/api/xapc/remuneration/caseRemuneration', {
      params
    }).then(res => {
      hide()
      if (res.status === 1) {
        const list = res.data.list.map((l, i) => {
          const date = moment(l.closure_datetime * 1000).format('YYYY-MM-DD')
          return {
            序号: pageSize * (current - 1) + i + 1,
            案号: l.caseno_desc,
            结案时间: date ? moment(date).toDate() : '',
            受理费: l.fee_acceptance,
            处理费: l.fee_processing,
            主办秘书: l.processer,
            // 仲裁员交通补贴: l.subsidy_amount,
            仲裁员报酬: l.real_amount,
            // 代扣会员费: l.membership_amount,
            // 仲裁员裁决书制作: l.closuredoc_amount,
            备注: l.remark
          }
        })
        list.push({
          序号: '',
          案号: '',
          结案时间: '',
          受理费: this.state.feeAcceptanceSum,
          处理费: this.state.feeProcessingSum,
          主办秘书: '',
          // 仲裁员交通补贴: this.state.subsidyAmountSum,
          仲裁员报酬: this.state.realAmountSum,
          // 代扣会员费: this.state.membershipAmountSum,
          // 仲裁员裁决书制作: this.state.closuredocAmountSum,
          备注: ''
        })
        json2Excel([{ data: list, sheetname: '结案收支表' }], '结案收支表')
      } else {
        return message.warning(res.message)
      }
    }).catch(() => hide())
  }

  changeProcesserid (v) {
    const list = this.state.employeeList
    for (let i = 0; i < list.length; i++) {
      if (list[i].name === v) {
        this.formRef.current.setFieldsValue({ processerid: list[i].id })
        break
      }
    }
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.initFormByMeta()
    this.initEmpolyeeList()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form
              name='doc_seal_list' {...layout} ref={this.formRef} onFinish={v => {
                this.setState({
                  selectedRowKeys: [],
                  selectedRows: []
                })
                this.getTableData(v)
              }}
            >
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='案号' name='caseno_desc'>
                    <Input placeholder='请输入案号' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='结案起始日期' name='beginTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='结案结束日期' name='endTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={8}>
                  <Item name='processerid' noStyle><span /></Item>
                  <Item label='主办秘书' name='processer'>
                    <Select placeholder='请选择' allowClear showSearch onChange={(v) => this.changeProcesserid(v)}>
                      {this.state.employeeList.map((li, i) => {
                        return (
                          <Option key={i} value={li.name}>{li.name}</Option>
                        )
                      })}
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='发起起始日期' name='oBeginTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='发起结束日期' name='oEndTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={24}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['download-btn-line']} style={{ marginBottom: '12px' }}>
          <Button type='primary' ghost onClick={() => this.confirmDownload()} icon={<DownloadOutlined />}>导出excel</Button>
          <span className={nStyle['other-info']}>
            <span>
              <span className={nStyle['ohter-info-label']}>总受理费：</span>
              <span className={nStyle['ohter-info-value']}>{formatMoney(this.state.feeAcceptanceSum)}</span>
            </span>
            <span>
              <span className={nStyle['ohter-info-label']}>总处理费：</span>
              <span className={nStyle['ohter-info-value']}>{formatMoney(this.state.feeProcessingSum)}</span>
            </span>
            {/* <span>
              <span className={nStyle['ohter-info-label']}>总仲裁员交通补贴：</span>
              <span className={nStyle['ohter-info-value']}>{formatMoney(this.state.subsidyAmountSum)}</span>
            </span> */}
            {/* <span>
              <span className={nStyle['ohter-info-label']}>总代扣会员费：</span>
              <span className={nStyle['ohter-info-value']}>{formatMoney(this.state.membershipAmountSum)}</span>
            </span>
            <span>
              <span className={nStyle['ohter-info-label']}>总仲裁员裁决书制作：</span>
              <span className={nStyle['ohter-info-value']}>{formatMoney(this.state.closuredocAmountSum)}</span>
            </span> */}
            <span>
              <span className={nStyle['ohter-info-label']}>总仲裁员报酬：</span>
              <span className={nStyle['ohter-info-value']}>{formatMoney(this.state.realAmountSum)}</span>
            </span>
          </span>
        </div>
        <div className={style['table-container']}>
          <Table
            loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)}
          />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(SimpleSearch)
